<template>
  <div class="queryRecords">
    <van-nav-bar
      :title="keyWord === 'wageSettlement' ? '查询（工资结算）' : `查询（${recordTypeObj_search[keyWord]}）`"
      left-arrow
      @click-left="$router.back()"
    />
    <com-search-by-date
      @getCalendarValue="toGetCalendarValue"
      :label="`${recordTypeObj_query[keyWord]}`"
    ></com-search-by-date>

    <!-- todo
        分类显示，
        第一类： 已报名、已工作；
        第二类： 我的下家， 第三类：我的关注
     -->

    <div class="jobArr" v-if="isShow && (keyWord === 'hasWorkedList' || keyWord === 'lendMoney')">
      <com-job-item
        v-for="(item, index) in 2"
        :key="index"
        :id="item"
        :keyWord="keyWord"
        :jobItem="needObj"
        :path="$route.path"
      ></com-job-item>
    </div>

    <div class="jobArr" v-if="isShow && keyWord === 'wageSettlement'">
      <com-job-item
        v-for="(item, index) in jobList"
        :key="index"
        :id="item"
        :keyWord="'wageSettlement'"
        :jobItem="item"
      ></com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'hasSignUpList'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-job-item
        :jobItem="item"
        :typeenrool="1"
        :keyWord="'hasSignUpList'"
        v-for="(item, index) in needObj"
        :key="index"
        @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
      ></com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'browsingHistory'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-job-item
        :jobItem="item"
        :typeenrool="1"
        :keyWord="'browsingHistory'"
        v-for="(item, index) in needObj"
        :key="index"
        @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
      ></com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'collectionHistory'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-job-item
        :jobItem="item"
        :typeenrool="1"
        :keyWord="'collectionHistory'"
        v-for="(item, index) in needObj"
        :key="index"
        @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
      ></com-job-item>
    </div>

    <div
      style="box-sizing: border-box; text-align: center; background-color: #FFFFFF; border-top: 1px solid #eee"
      v-if="isShow && keyWord === 'myAttention'"
    >
      <com-my-attention v-for="(item, index) in needObj" :data-item="item" :key="index"></com-my-attention>
    </div>
  </div>
</template>

<script>
import comJobItem from '../../components/comJobItem'
import comMyAttention from '../../components/comMyAttention'
import comSearchByDate from '../../components/comSearchByDate'
import {recordTypeObj_search, recordTypeObj_query} from '../../constants/comUtils'
import {obj} from '../../constants/comUtils'
import {Toast} from 'vant'
import {formatDate} from '@/utils/format'

export default {
  name: 'queryRecords',
  components: {
    comSearchByDate,
    comJobItem,
    comMyAttention
  },
  data() {
    return {
      needObj: {
        photos: [],
        educations: [],
        certificate_type: []
      },
      recordTypeObj_search,
      recordTypeObj_query,
      keyWord: '',
      isShow: false,
      searchParams: {
        keyword: '', // 搜索关键字
        lng: null, // 经度
        lat: null, // 维度
        cityId: '', // 城市ID
        streetId: '', // 街道ID
        jobcategory: '', // 招聘类型
        orderItem: '', // 排序字段
        minSalary: null, // 起始薪资
        maxSalary: null, // 最大薪资
        nearby: '', // 附近地址
        classproperties: '', // 班制属性
        jobattributes: '', // 职位属性
        benefits: '', // 福利列表
        paymode: '', // 算薪方式
        payday: '', // 发薪日
        payMoneyDetailDate: '', // 发薪日详细日期
        createTime: '', // 发布时间
        pageIndex: 1, // 当前页
        pageSize: 10, // 每页显示条数
        selectId: '',
        apptime: '' //已报名时间
      }, // 检索参数
      jobList: []
    }
  },

  created() {
    if (this.$route.params.id) {
      this.keyWord = this.$route.params.id
    } else {
      this.$router.back()
    }
  },

  methods: {
    async _getJobList() {
      let userInfo = JSON.parse(localStorage.getItem('userInfo'))
      const res = await this.$api.job.getJobBeenWorking({
        ...this.searchParams,
        UserId: userInfo.id
      })
      if (res.code === 200) {
        this.needObj = res.data.items
        this.total = res.data.count
        if (this.total == 0) this.totalType = 0
      }
    },
    toSaveBrowsingHistoryList(val) {
      // 仅用于点击首页的工作，点击保存记录
      // 若没有找到了, 则结果为undefined
      if (val) {
        val.recordTime = new Date()
      }
      this.saveBrowsingHistoryList.unshift(val)
      localStorage.setItem('saveBrowsingHistory', JSON.stringify(this.saveBrowsingHistoryList))
    },
    async _getMyAttention() {
      const res = await this.$api.job.getFollowList(this.searchParams)
      if (res.code === 200) {
        this.needObj = res.data.items
        this.total = res.data.count
        if (this.total == 0) this.totalType = 0
      }
    },
    toGetCalendarValue(val) {
      console.log('子组件到父组件的数据', val)
      this.searchParams.apptime = val
      if (this.keyWord === 'myAttention') {
        this._getMyAttention()
      } else if (this.keyWord === 'wageSettlement') {
        this._getWageSettlementJobsByDate()
      } else {
        this._getJobList()
      }
      this.isShow = true
    },
    toJobDetailPage(id) {
      console.log('已工作---子到父---进入详情', id)
      this.$router.push({
        path: `/jobDetail/${id}`
      })
    },

    //获取指定日期工资结算对应的工作信息
    async _getWageSettlementJobsByDate() {
      if (!this.searchParams.apptime) {
        Toast('请先选择发薪时间！')
        return
      }

      let date = new Date(this.searchParams.apptime + '-01')
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      if (month < 10) {
        month = '0' + month
      }
      let param = {
        keyword: `${year}-${month}-01`
      }

      const result = await this.$api.job.GetWageSettlementJobsByDate(param)
      if (result.code == 200) {
        let jobList = []
        for (let item of result.data.settlementJobInfoList) {
          let jobItem = {
            rowid: item.ids,
            id: item.id,
            ids: item.ids,
            enterprise_name: item.jobName,
            recruiting_position: item.recruitingPosition,
            min_comprehensive_salary: item.minComprehensiveSalary ? parseInt(item.minComprehensiveSalary) : 0,
            max_comprehensive_salary: item.maxComprehensiveSalary ? parseInt(item.maxComprehensiveSalary) : 0,
            payway_id: item.payWayId,
            job_category_id: item.jobCategoryId,
            create_time: formatDate(item.signUpTime, '-', ':'),
            status: item.status ? parseInt(item.status) : item.status,
            work_address_fulle_address: item.workAddressFulleAddress,
            fulle_address: item.fulleAddress,
            interview_address_fulle_address: item.interviewAddressFulleAddress,
            generation_instructions: item.generationInstructions,
            generation_of_commission: item.generationOfCommission,
            fee_unit: item.feeUnit,
            isLendMoney: 1,
            work_start_time: formatDate(item.startDate, '-', ':'),
            work_end_time: formatDate(item.overDate, '-', ':'),
            apply_time: formatDate(item.signUpTime, '-', ':'),
            first_value_input: item.firstValueInput,
            salaryuptime: formatDate(item.salaryTime, '-', ':'),
            salarymoney: item.salaryMoney,
            salaryInfoId: item.salaryInfoId,
            switch_state: item.switchState,
            job_status: item.jobStatus
          }

          jobList.push(jobItem)
        }

        this.jobList = jobList
      }
    }
  }
}
</script>

<style scoped></style>
